public class Main {
    /*
     * 二叉树的层序遍历（倒着）
     * BFS 双端队列
     * */
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        Deque<List<Integer>> deque = new LinkedList<>();
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> alist = new ArrayList<>();
            while (size > 0) {
                TreeNode node = queue.poll();
                alist.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            deque.addFirst(alist);
        }
        list.addAll(deque);
        return list;
    }

    /*
     * DFS
     *
     * */
    public static void levelOrder(TreeNode root, List<List<Integer>> lists, int deepth, int maxDeep) {
        if (root == null) {
            return;
        }
        levelOrder(root.left, lists, deepth + 1, maxDeep);
        levelOrder(root.right, lists, deepth + 1, maxDeep);
        lists.get(maxDeep - deepth).add(root.val);
    }

    public static List<List<Integer>> levelOrderBottom2(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        int maxDeep = Treehigh(root);
        for (int i = 0; i < maxDeep; i++) {
            list.add(new ArrayList<>());
        }
        levelOrder(root, list, 1, maxDeep);
        return list;
    }
}